package com.zust.ysc012.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @Description
 * @Author Mato
 * @Date 03/07/2021 04:11
 */
public class SetEncodingFilter implements Filter {
    protected FilterConfig config;
    protected String encoding = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        /* 从web.xml里读取编码配置好的初始值 */
        this.encoding = config.getInitParameter("Encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (encoding == null) {
            encoding = "UTF-8";
        }
        //将这三种编码设置后,请求/响应都不会出现乱码了
        servletResponse.setCharacterEncoding(encoding);
        servletRequest.setCharacterEncoding(encoding);
        servletResponse.setContentType("text/html;charset=" + encoding);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        encoding = null;
    }
}
